# Toolchain
CC       = riscv64-unknown-elf-gcc
LD       = riscv64-unknown-elf-ld
OBJCOPY  = riscv64-unknown-elf-objcopy

# Common arch/ABI/code-model
COMMON_FLAGS = -march=rv64gc -mabi=lp64d -mcmodel=medany

# Compile flags
CFLAGS  = -Wall -Werror -O2 -ffreestanding -nostdlib -nostartfiles \
          -fno-pic -no-pie -fdata-sections -ffunction-sections \
          -Iinclude $(COMMON_FLAGS)

ASFLAGS = -ffreestanding -nostdlib -nostartfiles $(COMMON_FLAGS)

# Linker flags
LDFLAGS = --gc-sections

# Sources and Objects
SRCS_KERNEL  = kernel/entry.S kernel/main.c kernel/uart.c kernel/printf.c kernel/console.c \
               kernel/kalloc.c kernel/vm.c
OBJS_KERNEL  = $(SRCS_KERNEL:.c=.o)
OBJS_KERNEL := $(OBJS_KERNEL:.S=.o)

.PHONY: all clean

all: kernel.bin

kernel.elf: $(OBJS_KERNEL) kernel/kernel.ld
	$(LD) $(LDFLAGS) -T kernel/kernel.ld -o $@ $(OBJS_KERNEL)

kernel.bin: kernel.elf
	$(OBJCOPY) -O binary $< $@

%.o: %.c
	$(CC) $(CFLAGS) -c $< -o $@

%.o: %.S
	$(CC) $(ASFLAGS) -c $< -o $@

clean:
	rm -f kernel.elf kernel.bin $(OBJS_KERNEL)